package com.tiyende.credit.loop.ui.activity

import android.annotation.SuppressLint
import android.view.View
import com.tiyende.credit.loop.R
import com.tiyende.credit.loop.common.CommonActivity
import com.tiyende.credit.loop.databinding.TiyendeActivityLoanCalculatorBinding
import com.tiyende.credit.loop.event.TiyendeEventPointType
import com.tiyende.credit.loop.ui.dialog.TiyendeCalculatorRepaymentTermDialog
import java.math.BigDecimal
import java.math.RoundingMode

/**
 * TiyendeCredit
 * @Author wwdeng
 * @CreateTime: 2025/1/27 13:34
 * @Annotation：贷款计算器
 */
class TiyendeLoanCalculatorActivity: CommonActivity() {
    lateinit var binding: TiyendeActivityLoanCalculatorBinding
    //是否开始计算
    var isCalculation = false
    var selectedRepaymentTerm = 0//还款期限
    var selectedInterestRate = 0//年利率
    override fun getTiyendeRootView(): View {
        binding = TiyendeActivityLoanCalculatorBinding.inflate(layoutInflater)
        return binding.root
    }

    override fun initTiyendeView() {
        setTiyendeTitleBarVisibility(View.VISIBLE)
        setTiyendeTextTitleVisibility(View.GONE)
        setTiyendeBackBtnRes(R.mipmap.tiyende_back_white)
        setTiyendeRightBtnRes(R.mipmap.tiyende_customer_white)
        showCalculatorCalculationView()
    }

    override fun initTiyendeListener() {
        //客服
        rootViewBinding.rootCustomer.setOnClickListener {
            val eventRemark = "Loan Calculator Page"
            showCustomerDialog(eventRemark)
            addEventPointRequestAction(TiyendeEventPointType.CLICK.TIYENDE_CLICK_CUSTOMER,eventRemark)
        }
        binding.calculatorChooseRepaymentTerm.setOnClickListener {
            val daysList = arrayListOf<String>()
            for (i in 100..260){
                daysList.add("$i")
            }
            TiyendeCalculatorRepaymentTermDialog(this)
                .setTiyendeCalculatorTitle(getString(R.string.tiyende_calculator_dialog_select_repayment_term))
                .setTiyendeCalculatorDataUnit(getString(R.string.tiyende_calculator_repayment_term_days_choose))
                .setTiyendeCalculatorEventRemark("Repayment_Term")
                .setTiyendeCalculatorData(daysList)
                .setTiyendeCalculatorClick(object : TiyendeCalculatorRepaymentTermDialog.ICalculatorDialogCallback{
                    override fun onConfirmItem(result: String) {
                        selectedRepaymentTerm = result.toInt()
                        binding.txtRepaymentTerm.text = String.format(getString(R.string.tiyende_calculator_repayment_term_days),result)
                        if (isCalculation){
                            binding.btCalculation.callOnClick()
                        }
                    }
                })
                .show()
        }
        binding.calculatorChooseInterestRate.setOnClickListener {
            val rateList = arrayListOf<String>()
            for (i in 12..26){
                rateList.add("$i")
            }
            TiyendeCalculatorRepaymentTermDialog(this)
                .setTiyendeCalculatorTitle(getString(R.string.tiyende_calculator_dialog_select_interest_rate))
                .setTiyendeCalculatorDataUnit("%")
                .setTiyendeCalculatorEventRemark("Interest_Rate")
                .setTiyendeCalculatorData(rateList)
                .setTiyendeCalculatorClick(object : TiyendeCalculatorRepaymentTermDialog.ICalculatorDialogCallback{
                    @SuppressLint("SetTextI18n")
                    override fun onConfirmItem(result: String) {
                        selectedInterestRate = result.toInt()
                        binding.txtInterestRate.text = "$result%"
                        if (isCalculation){
                            binding.btCalculation.callOnClick()
                        }
                    }
                })
                .show()
        }
        binding.btCalculation.setOnClickListener {
            if (getCalculatorLoanAmount().isEmpty()){
                showTiyendeToast(getString(R.string.tiyende_calculator_enter_amount))
                return@setOnClickListener
            }
            if (selectedRepaymentTerm == 0){
                showTiyendeToast("${getString(R.string.tiyende_calculator_select)} ${getString(R.string.tiyende_calculator_repayment_term)}")
                return@setOnClickListener
            }
            if (selectedInterestRate == 0){
                showTiyendeToast("${getString(R.string.tiyende_calculator_select)} ${getString(R.string.tiyende_calculator_interest_rate)}")
                return@setOnClickListener
            }
            isCalculation = true
            showCalculatorCalculationView()
        }

        binding.clearLayout.setOnClickListener {
            selectedRepaymentTerm = 0
            selectedInterestRate = 0
            binding.editCalculatorLoanAmount.setText("")
            binding.txtRepaymentTerm.text = ""
            binding.txtInterestRate.text = ""

            isCalculation = false
            showCalculatorCalculationView()
        }
    }

    override fun loadTiyendeData() {
    }

    @SuppressLint("SetTextI18n")
    private fun showCalculatorCalculationView(){
        when(isCalculation){
            true -> {
                binding.calculationResultLayout.visibility = View.VISIBLE
                binding.repayTotalLayout.visibility = View.VISIBLE
                binding.txtLoanAmount.text = getCalculatorLoanAmount()
                //日利率
                val dailyInterest = BigDecimal(selectedInterestRate).divide(BigDecimal(365),2, RoundingMode.HALF_UP).toPlainString().toDouble()
                binding.txtDailyInterest.text = "$dailyInterest%"
                binding.txtRepaymentTerm2.text = String.format(getString(R.string.tiyende_calculator_repayment_term_days),"$selectedRepaymentTerm")
                val totalInterest = BigDecimal(getCalculatorLoanAmount()).multiply(BigDecimal(dailyInterest)).multiply(BigDecimal(selectedRepaymentTerm)).divide(BigDecimal(100),2,RoundingMode.HALF_UP).toPlainString()
                binding.txtRepayAmount.text = BigDecimal(getCalculatorLoanAmount()).add(BigDecimal(totalInterest)).stripTrailingZeros().toPlainString()

                binding.btCalculation.text = getString(R.string.tiyende_calculator_btn_recalculate)
                binding.clearLayout.visibility = View.VISIBLE
            }
            else -> {
                binding.calculationResultLayout.visibility = View.GONE
                binding.repayTotalLayout.visibility = View.GONE

                binding.btCalculation.text = getString(R.string.tiyende_calculator_btn_start_calculation)
                binding.clearLayout.visibility = View.GONE
            }
        }
    }

    private fun getCalculatorLoanAmount(): String{
        return binding.editCalculatorLoanAmount.text.toString()
    }

    override fun onStart() {
        super.onStart()
        addEventPointRequestAction(TiyendeEventPointType.PAGE.TIYENDE_PAGE_LOAN_CALCULATOR_START)
    }

    override fun onDestroy() {
        super.onDestroy()
        addEventPointRequestAction(TiyendeEventPointType.PAGE.TIYENDE_PAGE_LOAN_CALCULATOR_END)
    }
}